/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.webbapps.cormac_susilo.upload;

import edu.webbapps.cormac_susilo.core.IUserModel;
import edu.webbapps.cormac_susilo.wrappers.UserWrapper;
import java.io.IOException;
import java.io.InputStream;
import java.util.NoSuchElementException;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.inject.Inject;
import javax.persistence.RollbackException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;

/**
 * 
 * The Upload Servlet will take care of the file from the form and
 * ask the modelapi to decode the file and update the user.
 * 
 * see: http://commons.apache.org/proper/commons-fileupload/using.html
 *
 * @author tor
 */
@WebServlet(name = "UploadServlet", urlPatterns = {"/upload"})
public class UploadServlet extends HttpServlet {

    @Inject
    private IUserModel mgr;

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        throw new UnsupportedOperationException("processRequest is not implemneted");
    }

    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // Ensure it is multipart
        boolean ismultipart = ServletFileUpload.isMultipartContent(request);
        if (ismultipart) {
            try {

                HttpSession session = request.getSession();
                Long user_id = (Long) session.getAttribute("user");
                //authenticated by AuthFilter

                if (user_id == null) {
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
                    return;
                }

                UserWrapper foundUser = mgr.getUser(user_id);
                
                /*
                 * We will read it as a stream, which makes it a little
                 * awkward, because we make no assumption of field order.
                 * 
                 * TODO Should rewrite this using FileItemFactory
                 */
                ServletFileUpload upload = new ServletFileUpload();
                FileItemIterator iter = upload.getItemIterator(request);

                // Generate a random trackname
                Random r = new Random(System.currentTimeMillis());
                char[] rnd = new char[32];
                for (int i = 0; i < 32; i++) {
                    rnd[i] = (char) (r.nextInt(26) + 'a');
                }
                
                // These are the variables we require
                String temp_trackname = String.valueOf(rnd);
                String trackname = null;

                // Process the uploaded file / form fields
                while (iter.hasNext()) {
                    FileItemStream item = iter.next();
                    String name = item.getFieldName();
                    InputStream stream = item.openStream();

                    if (item.isFormField()) {
                        //assert
                        if (name.equals("trackname")) {
                            trackname = Streams.asString(stream);
                        } else {
                            // ignore content
                            Streams.asString(stream); 
                        }

                    } else {
                        // It is afile
                        Logger.getLogger(UploadServlet.class.getName()).log(Level.INFO, "Reading filestream as " + temp_trackname);
                        // Read the data...
                        mgr.uploadFile(user_id, stream, temp_trackname);
                    }
                }

                // update to appropriate trackname
                if (trackname == null || trackname.length() == 0 || trackname.length() > 32) {
                    trackname = IUserModel.DEFAULT_RUNNAME;
                }
                // rename the track
                mgr.renameRuns(user_id, temp_trackname, trackname);

                response.sendRedirect("user.jsp?user=" + foundUser.getId());

            } catch (FileUploadException ex) {
                Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex);
                response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            } catch (RollbackException e) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            } catch (NoSuchElementException e) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
            }
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
